package com.umgsai.wx.backend.test;

public class KthSmallest {

    private int count = 0;
    private int result = 0;

    public int kthSmallest(TreeNode root, int k) {
        midOrder(root, k);
        return result;
    }

    // 中序遍历
    public void midOrder(TreeNode root, int k) {
        if (root == null || count > k) {
            return;
        }
        if (root.left != null) {
            midOrder(root.left, k);
        }
        count++;
        if (count == k) {
            result = root.val;
        }
        if (root.right != null) {
            midOrder(root.right, k);
        }
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
